#!/bin/sh

do_help() {
    echo "$0 scanlist" >&2
    echo "$0 list" >&2
}

do_list() {
    connmanctl services | sed 's/^...[ ]*//' | awk -F '[ ]*[ ]wifi_[[:alnum:]]*_' '{if (NF==2) print $1}' | sort -u # remove duplicates (a single wifi can appear under 2 interfaces)
}

do_scanlist() {
    connmanctl scan wifi >/dev/null 2>/dev/null
    do_list
}

wait_for_ip() {
    local mode=$1

    for i in $(seq 1 20); do
        if [ "$mode" = "up" ]; then
            if ip -4 addr show | grep "inet " | grep -qv "127\.0\.0\.1"; then
                break
            fi
        elif [ "$mode" = "down" ]; then
            if ! ip -4 addr show | grep "inet " | grep -qv "127\.0\.0\.1"; then
                break
            fi
        fi
        sleep 0.5
    done
}

if [ $# -eq 0 ]; then
    do_help
    exit 1
fi

ACTION=$1
shift

case "${ACTION}" in
    "list")
        do_list
        ;;
    "scanlist")
        do_scanlist
        ;;
    "start")
        /etc/init.d/S08connman restart
        ;;
    "enable")
        batocera-settings-set wifi.enabled 1
        
        if [ $# -eq 3 ]; then
            batocera-settings-set wifi.ssid "$1"
            batocera-settings-set wifi.key "$2"
            batocera-settings-set wifi.country "$3"

            if [ -n "$3" ]; then
                iw reg set "$3"
            fi
        fi

        /etc/init.d/S08connman reload

        settings_ssid="$(batocera-settings-get wifi.ssid)"

        # We don't need to wait for an IP if no saved ssid
        if [ -n "${settings_ssid}" ]; then
            wait_for_ip up
        else
            sleep 1 # wait 1 second for connman to initialize and start scanning
        fi
        ;;
    "disable")
        batocera-settings-set wifi.enabled 0
        /etc/init.d/S08connman reload
        wait_for_ip down
        ;;
    *)
        do_help
        >&2 echo "error: invalid command ${ACTION}"
        exit 1
        ;;
esac

exit 0
